<?php

namespace App\Traits;

use App\Common\Constant;
use Gregwar\Captcha\CaptchaBuilder;
use Gregwar\Captcha\PhraseBuilder;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Hash;

/**
 * 图形验证码 Trait
 *
 * @author: WangBin
 * @date: 2021/9/16
 */
trait CaptchaTrait
{
    /**
     * 生成图形验证码，存入缓存，返回文件名
     *
     * @param int $entityId
     * @return
     */
    public function createCaptcha(int $entityId)
    {
        $phrase = new PhraseBuilder;
        // 设置验证码位数
        $code = $phrase->build(5);
        // 生成验证码图片的Builder对象,配置相应属性
        $builder = new CaptchaBuilder($code, $phrase);
        // 设置背景颜色25,25,112
        $builder->setBackgroundColor(25, 25, 112);
        // 设置倾斜角度
        $builder->setMaxAngle(25);
        // 设置验证码后面最大行数
        $builder->setMaxBehindLines(10);
        // 设置验证码前面最大行数
        $builder->setMaxFrontLines(10);
        // 设置验证码颜色
        $builder->setTextColor(255, 255, 0);
        // 可以设置图片宽高及字体
        $builder->build($width = 150, $height = 40, $font = null);

        // 获取验证码的内容
        $phrase = $builder->getPhrase();
        $key = Constant::CAPTCHA_PREFIX . $entityId;
        // 存入缓存
        Cache::put($key, $phrase, Constant::CAPTCHA_TTL);

        // 生成图片
        $filename = storage_path('/captcha/') . $key . '.jpg';
        $builder->save($filename);
        return ['filename' => $filename, 'hash' => Hash::make()];
    }
}